package com.njust.component;

import com.njust.dao.DepartmentDao;
import com.njust.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyStringToEmployee implements Converter<String, Employee> {

    @Autowired
    private DepartmentDao departmentDao;
    /**
     *
     * @param source 张三-zhangsan@163.com-1-2019/11/12-1000.20-101"
     * @return
     */
    @Override
    public Employee convert(String source) {

        System.out.println("原来的数据：" + source);
        if (source != null && source.contains("-")){
            String[] splits = source.split("-");
            Employee employee = new Employee();
            employee.setLastName(splits[0]);
            employee.setEmail(splits[1]);
            employee.setGender(Integer.parseInt(splits[2]));
            SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
            Date date = null;
            try {
                 date = format.parse(splits[3]);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            employee.setBirth(date);
            System.out.println("日期为：" + date.toString());
            employee.setSalary(Double.parseDouble(splits[4]));
            employee.setDepartment(departmentDao.getDepartment(Integer.parseInt(splits[5])));
            return employee;
        }
        return null;
    }
}
